#include <copi_oswindow.h>
#include <copi_ui.h>
#include <lauxlib.h>
#include <lua.h>
#include <lualib.h>
#include <stdio.h>

static struct oswindow windata = { 0 };
static lua_State*      lstate;

static int msghandler( lua_State* L )
{
    const char* msg = lua_tostring( L, 1 );
    if ( msg == NULL ) {
        if ( luaL_callmeta( L, 1, "__tostring" ) && lua_type( L, -1 ) == LUA_TSTRING )
            return 1;
        else
            msg = lua_pushfstring( L, "(error object is a %s value)", luaL_typename( L, 1 ) );
    }
    luaL_traceback( L, L, msg, 1 );
    return 1;
}

static int docall( lua_State* L, int narg, int nres )
{
    int status;
    int base = lua_gettop( L ) - narg;
    lua_pushcfunction( L, msghandler );
    lua_insert( L, base );
    status = lua_pcall( L, narg, nres, base );
    lua_remove( L, base );
    return status;
}

static void copi_oswindow_loop_callback( int w, int h )
{
    // update function call
    lua_getglobal( lstate, "copi_update" );
    lua_pushnumber( lstate, w );
    lua_pushnumber( lstate, h );
    int rvl = docall( lstate, 2, 0 );
    if ( rvl != 0 ) {
        printf( "init 失败, %d", rvl );
        printf( "%s", lua_tostring( lstate, -1 ) );
    }
}

static int copi_oswindow_close( lua_State* L )
{
    copi_os_window_close( &windata );
    return 0;
}

static int copi_oswindow_loop( lua_State* L )
{
    lstate = L;
    copi_os_window_loop( &windata, &copi_oswindow_loop_callback );
    return 0;
}

static int copi_oswindow_open( lua_State* L )
{
    windata.bg [0] = 1;
    windata.bg [1] = 0;
    windata.bg [2] = 0;
    windata.bg [3] = 1;
    copi_os_window_open( &windata );
    return 0;
}

static int copi_oswindow_change_bg( lua_State* L )
{
    double r = lua_tonumber( L, 1 );
    double g = lua_tonumber( L, 1 );
    double b = lua_tonumber( L, 1 );
    double a = lua_tonumber( L, 1 );

    windata.bg [0] = r;
    windata.bg [1] = g;
    windata.bg [2] = b;
    windata.bg [3] = a;

    return 0;
}

static int luaopen_ui( lua_State* L )
{
    luaL_Reg l [] = { { "window_begin", copi_ui_window_begin },
                      { "window_end", copi_ui_window_end },
                      { "button", copi_ui_button },
                      { "color_button", copi_ui_color_button },
                      { "text", copi_ui_text },
                      { "separator_text", copi_ui_separator_text },
                      { "sameline", copi_ui_sameline },
                      // { "main_window_open", copi_oswindow_open },
                      // { "main_window_close", copi_oswindow_close },
                      // { "main_window_loop", copi_oswindow_loop },
                      { "main_window_change_bg", copi_oswindow_change_bg },
                      { "theme_light", copi_theme_light },
                      { "theme_dark", copi_theme_dark },
                      { "theme_classic", copi_theme_classic },
                      { NULL, NULL } };
    luaL_newlib( L, l );
    return 1;
}
